<template>
	<view class="container">
		<!-- 顶部按钮 -->
		<view class="top-action">
			<button class="help-button" @tap="askForHelp">
				<text class="help-icon">●</text>
				<text class="help-text">求助好友</text>
			</button>
		</view>
		
		<!-- 成语题目区 -->
		<view class="quiz-content">
			<view class="quiz-area">
				<view class="idiom-display">
					{{ currentQuestion.name || '加载中...' }}
				</view>
				
				<!-- 倒计时显示 -->
				<view class="countdown-container">
					<view class="countdown-bar" :style="{ width: (countdown / 20 * 100) + '%' }"></view>
					<text class="countdown-text">{{ countdown }}秒</text>
				</view>
				
				<view class="options-container" v-if="currentQuestion.options && currentQuestion.options.length">
					<view 
						v-for="(option, index) in currentQuestion.options" 
						:key="index"
						class="option-box" 
						:class="{
							'selected': selectedOption === index, 
							'correct': showAnswer && index === currentQuestion.answer, 
							'incorrect': showAnswer && selectedOption === index && index !== currentQuestion.answer
						}"
						@tap="handleOptionTap(index)"
					>
						{{ option }}
					</view>
				</view>

				<view class="loading" v-else>
					<text>加载题目中...</text>
				</view>
			</view>
			
			<!-- 底部状态栏 -->
			<view class="bottom-status">
				<view class="status-item">
					<text class="status-icon">●</text>
					<text class="status-text">答题卡: <text class="status-value">{{ userStats.cards }}</text></text>
				</view>
				<view class="status-item">
					<text class="status-icon star">★</text>
					<text class="status-text">积分: <text class="status-value">{{ userStats.points }}</text></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentQuestion: {
					name: '',
					options: [],
					answer: -1
				},
				questionId: '',
				selectedOption: -1,
				showAnswer: false,
				userStats: {
					cards: 14,
					points: 235
				},
				isLoading: false,
				countdown: 20,         // 倒计时秒数
				countdownTimer: null,   // 倒计时定时器
				isActive: true          // 页面是否活跃
			}
		},
		onLoad() {
			// 页面加载时获取题目
			this.loadRandomQuestion();
		},
		onShow() {
			// 页面显示时，标记为活跃状态
			this.isActive = true;
			
			// 如果当前没有题目或已经显示答案，则加载新题目
			if (!this.currentQuestion.name || this.showAnswer) {
				this.loadRandomQuestion();
			} else {
				// 否则重新开始倒计时
				this.resetCountdown();
			}
		},
		onHide() {
			// 页面隐藏时，标记为非活跃状态并停止倒计时
			this.isActive = false;
			this.clearCountdownTimer();
		},
		onUnload() {
			// 页面卸载时清除定时器
			this.isActive = false;
			this.clearCountdownTimer();
		},
		methods: {
			// 处理选项点击
			handleOptionTap(index) {
				this.selectOption(index);
			},
			
			// 加载随机题目
			async loadRandomQuestion() {
				// 如果页面不活跃，不加载新题目
				if (!this.isActive) return;
				
				this.isLoading = true;
				this.showAnswer = false;
				this.selectedOption = -1;
				// 重置并开始倒计时
				this.resetCountdown();
				
				try {
					// 调用云对象获取随机题目
					const questionCloud = uniCloud.importObject('question-info-co');
					const result = await questionCloud.getRandomQuestion();
					
					if (result.code === 0 && this.isActive) { // 仅当页面活跃时更新UI
						// 从数据库获取数据
						const questionData = result.data;
						console.log('从云对象获取题目:', JSON.stringify(questionData));
						
						// 数据库中answer从1开始，需要减1使其与数组索引(从0开始)匹配
						const originalAnswer = parseInt(questionData.answer);
						const adjustedAnswer = originalAnswer - 1; // 将1开始的索引转为0开始
						
						// 输出调试信息
						console.log('数据库答案索引(从1开始):', originalAnswer);
						console.log('调整后答案索引(从0开始):', adjustedAnswer);
						console.log('选项:', JSON.stringify(questionData.options));
						console.log('正确答案:', questionData.options[adjustedAnswer]);
						
						// 修改答案索引以匹配前端数组
						this.currentQuestion = {
							...questionData,
							answer: adjustedAnswer
						};
						this.questionId = questionData._id;
					} else if (!this.isActive) {
						console.log('页面不活跃，不更新UI');
					} else {
						throw new Error(result.message || '获取题目失败');
					}
				} catch (error) {
					if (this.isActive) { // 仅当页面活跃时显示错误
						uni.showToast({
							title: error.message || '获取题目失败',
							icon: 'none'
						});
						console.error('获取题目失败:', error);
					}
				} finally {
					this.isLoading = false;
				}
			},
			
			// 重置并开始倒计时
			resetCountdown() {
				// 如果页面不活跃，不启动倒计时
				if (!this.isActive) return;
				
				// 清除现有定时器
				this.clearCountdownTimer();
				
				// 重置倒计时
				this.countdown = 20;
				
				// 开始新的倒计时
				this.countdownTimer = setInterval(() => {
					// 如果页面不活跃，不继续倒计时
					if (!this.isActive) {
						this.clearCountdownTimer();
						return;
					}
					
					if (this.countdown > 0) {
						this.countdown--;
					}
					if (this.countdown === 0) {
						// 时间到，自动跳到下一题
						this.clearCountdownTimer();
						
						// 仅当页面活跃时显示提示并加载下一题
						if (this.isActive) {
							uni.showToast({
								title: '时间到！',
								icon: 'none'
							});
							
							// 如果还没选择答案，显示正确答案
							if (!this.showAnswer) {
								this.showAnswer = true;
								
								// 延迟后加载下一题
								setTimeout(() => {
									if (this.isActive) { // 再次检查页面活跃状态
										this.loadRandomQuestion();
									}
								}, 1500);
							}
						}
					}
				}, 1000);
			},
			
			// 清除倒计时定时器
			clearCountdownTimer() {
				if (this.countdownTimer) {
					clearInterval(this.countdownTimer);
					this.countdownTimer = null;
				}
			},
			
			// 选择答案
			selectOption(index) {
				// 如果已经选择或正在显示答案，不允许再次选择
				if (this.selectedOption !== -1 || this.showAnswer || !this.isActive) {
					return;
				}
				
				// 停止倒计时
				this.clearCountdownTimer();
				
				this.selectedOption = index;
				this.showAnswer = true;
				
				console.log('您选择了:', index);
				console.log('正确答案索引:', this.currentQuestion.answer);
				
				// 检查答案
				if (index === parseInt(this.currentQuestion.answer)) {
					// 答对增加积分
					this.userStats.points += 10;
					
					uni.showToast({
						title: '正确 +10积分',
						icon: 'success'
					});
					
					// 延迟后加载下一题
					setTimeout(() => {
						if (this.isActive) { // 仅当页面活跃时加载下一题
							this.loadRandomQuestion();
						}
					}, 1500);
				} else {
					uni.showToast({
						title: '回答错误',
						icon: 'none'
					});
					
					// 延迟后加载下一题
					setTimeout(() => {
						if (this.isActive) { // 仅当页面活跃时加载下一题
							this.loadRandomQuestion();
						}
					}, 1500);
				}
			},
			
			// 向好友求助
			askForHelp() {
				if (!this.isActive || this.userStats.cards <= 0) {
					uni.showToast({
						title: '答题卡不足',
						icon: 'none'
					});
					return;
				}
				
				uni.showModal({
					title: '求助好友',
					content: '是否花费1张答题卡向好友求助？',
					success: (res) => {
						if (res.confirm && this.isActive) { // 仅当页面活跃时执行后续操作
							// 扣除一张答题卡
							this.userStats.cards--;
							
							// 模拟向好友求助
							setTimeout(() => {
								if (this.isActive) { // 再次检查页面活跃状态
									// 提示正确答案
									const correctOption = this.currentQuestion.options[this.currentQuestion.answer];
									uni.showModal({
										title: '好友提示',
										content: `正确答案是：${correctOption}`,
										showCancel: false
									});
								}
							}, 500);
						}
					}
				});
			}
		}
	}
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		background-image: linear-gradient(135deg, #67b3ff 0%, #ffffff 100%);
		min-height: 100vh;
	}
	
	/* 顶部按钮 */
	.top-action {
		display: flex;
		justify-content: flex-end;
		padding: 30rpx 30rpx 0;
	}
	
	.help-button {
		background-color: #3b82f6;
		color: white;
		border-radius: 40rpx;
		padding: 12rpx 24rpx;
		display: flex;
		align-items: center;
		font-size: 26rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.help-icon {
		margin-right: 6rpx;
		font-size: 20rpx;
	}
	
	/* 成语题目区域 */
	.quiz-content {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
		flex: 1;
		margin-top: 20rpx;
		padding: 20rpx;
	}
	
	.quiz-area {
		background-color: rgba(255, 255, 255, 0.8);
		border-radius: 20rpx;
		padding: 40rpx;
		width: 90%;
		display: flex;
		flex-direction: column;
		align-items: center;
		box-shadow: 0 6rpx 15rpx rgba(0, 0, 0, 0.1);
	}
	
	.idiom-display {
		font-size: 60rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		padding: 40rpx;
		border: 4rpx dashed #fca5a5;
		border-radius: 16rpx;
		background-color: #feecec;
	}
	
	/* 倒计时样式 */
	.countdown-container {
		width: 90%;
		height: 40rpx;
		background-color: #f0f0f0;
		border-radius: 20rpx;
		margin-bottom: 40rpx;
		position: relative;
		overflow: hidden;
		box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
	}
	
	.countdown-bar {
		height: 100%;
		background-image: linear-gradient(to right, #f87171, #fb923c);
		border-radius: 20rpx;
		transition: width 1s linear;
	}
	
	.countdown-text {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		font-size: 24rpx;
		color: #333;
		font-weight: bold;
	}
	
	.options-container {
		display: flex;
		justify-content: center;
		flex-wrap: wrap;
		gap: 20rpx;
	}
	
	.option-box {
		width: 120rpx;
		height: 120rpx;
		border: 2rpx solid #f87171;
		background-color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
	}
	
	.option-box.selected {
		background-color: #fef3c7;
	}
	
	.option-box.correct {
		background-color: #dcfce7;
		border-color: #22c55e;
	}
	
	.option-box.incorrect {
		background-color: #fee2e2;
		border-color: #ef4444;
	}
	
	.loading {
		padding: 30rpx;
		color: #666;
	}
	
	/* 底部状态栏 */
	.bottom-status {
		display: flex;
		justify-content: space-around;
		width: 100%;
		padding: 30rpx 0;
		margin-top: 60rpx;
		background-color: rgba(255, 255, 255, 0.8);
		border-radius: 16rpx;
	}
	
	.status-item {
		display: flex;
		align-items: center;
	}
	
	.status-icon {
		color: #f97316;
		margin-right: 10rpx;
		font-size: 28rpx;
	}
	
	.status-icon.star {
		color: #facc15;
	}
	
	.status-text {
		font-size: 28rpx;
		color: #333;
	}
	
	.status-value {
		font-weight: bold;
	}
</style> 